<template>
  <div id="app">
    <van-nav-bar
      v-if="!iswx && !$route.meta.hide"
      :title="title"
      :left-arrow="!$route.meta.hideLeftArrow"
      @click-left="$router.back()"
      fixed
      :border="false"
    />
    <transition :name="transitionName">
      <keep-alive :include="includePageNames.toString()">
        <router-view class="Router" :style="!iswx && !$route.meta.hide ? 'top: 46px;' : ''" />
      </keep-alive>
    </transition>
    <myTabbar v-if="showTabbar"></myTabbar>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import myTabbar from "./views/components/myTabbar";
var _self;
// TODO: 测试todo的内容
export default {
  name: "app",
  data() {
    let webview = this.slow.isWebview();
    this.iswx = webview === "wechat-android" || webview === "wechat-ios";
    return {
      // keepAlive: "main-keep-alive", //需要缓存的页面 例如首页
      transitionName: "slide-right", //初始过渡动画方向
      tabbars: ["home", "transfer", "my"],
      showTabbar: true,
      wxcode: "",
      location: {
        latitude: "", // 纬度，浮点数，范围为90 ~ -90
        longitude: "",
        speed: "",
        accuracy: "",
        err: ""
      }
    };
  },
  components: {
    myTabbar: myTabbar
  },
  computed: {
    ...mapGetters(["includePageNames", "title"])
  },
  watch: {
    $route(to, from) {
      this.wx.checkJsSdk();
      this.setTitle(to.meta.explain);
      // 修改历史动画
      let pags = this.includePageNames.toString();
      let tabbars = ["home", "activity", "my"];
      if (tabbars.indexOf(to.name) != -1 && tabbars.indexOf(from.name) != -1) {
        if (tabbars.indexOf(to.name) > tabbars.indexOf(from.name)) {
          this.transitionName = "slide-right";
        } else {
          this.transitionName = "slide-left";
        }
      } else if (pags.indexOf(to.name) != -1) {
        this.transitionName = "slide-left";
      } else {
        this.transitionName = "slide-right";
      }
      // 控制tabbar 展示与否
      if (this.tabbars.indexOf(to.name) === -1) {
        this.showTabbar = false;
      } else {
        this.showTabbar = true;
      }
    }
  },
  /**
   * 'jssdk注册成功'
   */
  wxReady() {
    wx.getLocation({
      type: "wgs84", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
      success: function(res) {
        if (res.latitude) {
          var geocode = new T.Geocoder();
          geocode.getLocation(
            new T.LngLat(res.longitude, res.latitude),
            ret => {
              res.address = ret.getAddress();
              _self.slow.setApiData("location", res);
              console.info("当前地址", res);
            }
          );
        }
      }
    });
  },
  created() {
    _self = this;
    // 微信签名验证
    this.wx.checkJsSdk();
    // 获取code ,拉取用户信息openId
    this.wxcode = this.getUrlParam("code");
    // sessionStorage.setItem("wxCode", this.wxcode);
    this.requestAuthorization();
  },
  methods: {
    // 请求获取用户信息
    requestAuthorization() {
      if(window.localStorage.getItem("isAuthflag") === "1"){
        // if(false){
        // isAuth
        sessionStorage.setItem("isAuth", true);
        _self.slow.setApiData("isAuth", true);
        // dataAreaCode
        console.log('dataAreaCode的sessionStorage.getItem：',sessionStorage.getItem("dataAreaCode"));
        let dataAreaCode = window.localStorage.getItem("dataAreaCode");
        sessionStorage.setItem("dataAreaCode", dataAreaCode);
        // _self.slow.setApiData("dataAreaCode", dataAreaCode);
        console.log('dataAreaCode的sessionStorage.getItem：',sessionStorage.getItem("dataAreaCode"));

        // authObject
        let authObject = JSON.parse(window.localStorage.getItem("authObject"));
        sessionStorage.setItem("authObject", JSON.stringify(authObject));
        _self.slow.setApiData("authObject", authObject);
        console.log('authObject的sessionStorage.getItem：',sessionStorage.getItem("authObject"));
        console.log('slow.authObject',this.slow.authObject)
        // userInfo
        let userInfo = JSON.parse(window.localStorage.getItem("userInfo"));
        sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
         _self.slow.setApiData("userInfo", userInfo);
         console.log('userInfo的sessionStorage.getItem：',sessionStorage.getItem("userInfo"));
         console.log('slow.userInfo是：',userInfo)
      }else{
        this.post("community_activity/tologin/userinfo?code=" + this.wxcode)
        .then(res => {
          console.log("userinfo接口获取信息",res)
          sessionStorage.setItem("userInfo", JSON.stringify(res.object));
          window.localStorage.setItem("userInfo", JSON.stringify(res.object));
          _self.slow.setApiData("userInfo", res.object);
          // 校验系统用户信息，是否已完善信息
          this.post("publicUser/loginPublicUser", {
            wxid: this.slow.userInfo.openId
            // wxid:'ohOIg1HGqunD7mo2QT5DIxKO7GKs'
          })
            .then(res => {
              console.log("loginPublicUser接口获取信息",res)
              if(res.success){
                window.localStorage.setItem("isAuthflag", "1");
              }
              //dataAreaCode
              res.object.dataAreaCode && sessionStorage.setItem("dataAreaCode", res.object.dataAreaCode);
              res.object.dataAreaCode && window.localStorage.setItem("dataAreaCode", res.object.dataAreaCode);
              //isAuth
              sessionStorage.setItem("isAuth", res.success);
              _self.slow.setApiData("isAuth", res.success);
              // sessionStorage.setItem("isAuth", true);
              // _self.slow.setApiData("isAuth", true);
              //authObject
              window.localStorage.setItem("authObject", JSON.stringify(res.object));
              _self.slow.setApiData("authObject", res.object);
              
            })
            .catch(err => {
              console.log(err.toString());
            });
        })
        .catch(err => {
          console.log(err.toString());
        });
      }
    },

    // 解析url参数并获取code this.getUrlParam("code")
    getUrlParam(name) {
      //name为要获取的参数名
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var rrr = decodeURIComponent(window.location.search);
      var r = rrr.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    }
  }
};
</script>
<style lang="scss">
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  margin: auto;
  position: relative;
  .Router {
    position: fixed;
    transition: all 0.377s ease;
    will-change: transform;
    top: 0;
    bottom: 0;
    overflow-y: scroll;
    width: 100%;
    backface-visibility: hidden;
    perspective: 1000;
  }
  .slide-left-enter,
  .slide-right-leave-active {
    opacity: 0;
    transform: translate3d(-100%, 0, 0);
  }

  .slide-left-leave-active,
  .slide-right-enter {
    opacity: 0;
    transform: translate3d(100%, 0, 0);
  }
}

.van-icon.van-icon-arrow-left.van-nav-bar__arrow {
  color: #333;
  font-size: 20px;
}
</style>

